package me.tgl.demo1.exception.handler;

import me.tgl.demo1.exception.MyException;
import me.tgl.demo1.model.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2017/7/14.
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> myExceptionHandler(HttpServletRequest req, MyException e) throws Exception {
        ErrorInfo<String> err = new ErrorInfo<>();
        err.setMessage(e.getMessage());
        err.setCode(ErrorInfo.ERROR);
        err.setData("?????????");
        err.setUrl(req.getRequestURL().toString());
        return err;
    }
}
